package org.wattdepot.cli.command;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.client.WattDepotClient;
import org.wattdepot.resource.property.jaxb.Property;
import org.wattdepot.resource.sensordata.jaxb.SensorData;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.util.tstamp.Tstamp;

/**
 * Implements the SensorData command handler.
 * 
 * @author Yichi Xu
 *
 */
public class SensorDataCommand extends WattDepotCliCommand {
  /**
   * Creates an instance of the SensorData command handler.
   * 
   * @param client An instance of the WattDepotClient.
   */
  public SensorDataCommand(WattDepotClient client) {
    super(client);
  }
  
  /**
   * List the sensor data given a timestamp.
   * Returns an error message if one occurs.
   * 
   * @param command The command to process.
   * @return The result of the command.
   */
  @Override
  public String doCommand(String command) {
    StringTokenizer tokenizer = new StringTokenizer(command);
    List<String> tokens = new ArrayList<String>();
    XMLGregorianCalendar timestamp = null;

    while (tokenizer.hasMoreTokens()) {
      tokens.add(tokenizer.nextToken());
    }
    
    if (tokens.size() != 4) {
      return this.reportError(PARAMETER_COUNT_ERROR);
    }
    
    if (!"sensordata".equals(tokens.get(0))) {
      return WattDepotCliCommand.reportUnknownCommand(command);
    }
    
    if (!"timestamp".equals(tokens.get(2))) {
      return this.reportError(PARAMETER_ERROR + tokens.get(2));
    }
    try {
      timestamp = Tstamp.makeTimestamp(tokens.get(3));
    }
    catch (Exception ex) {
      return this.reportError(TSTAMP_ERROR + tokens.get(3));
    }
    try {
      return this.listSensorDataTimestamp(tokens.get(1), timestamp);
    }
    catch (ResourceNotFoundException ex) {
      return this.reportError(SOURCE_ERROR + tokens.get(1));
    }
    catch (BadXmlException ex) {
      return this.reportError(BAD_XML_ERROR);
    }
    catch (Exception ex) {
      return this.reportError(CONNECTION_ERROR);
    }
  }
  
  /**
   * List sensor data given a timestamp.
   * @param sourceName the name of the source
   * @param timestamp the timestamp of the request
   * @return the message that contains the information of 
   * the sensor data give the specific timestamp
   * @throws MiscClientException Exception
   * @throws BadXmlException Exception
   * @throws ResourceNotFoundException Exception
   * @throws NotAuthorizedException Exception
   */
  private String listSensorDataTimestamp(String sourceName, XMLGregorianCalendar timestamp) 
  throws NotAuthorizedException, ResourceNotFoundException, BadXmlException, MiscClientException {
    StringBuffer buf = new StringBuffer();
    SensorData sensorData = client.getSensorData(sourceName, timestamp);
    String format = " %1$s: %2$s \n";
    buf.append(String.format(format, "Tool", sensorData.getTool()));
    String source = sensorData.getSource();
    String propertyString;
    Double power;
    
    while (source.contains("/")) {
      source = source.substring(source.indexOf('/') + 1);
    }
    
    buf.append(String.format(format, "Source", source));
    StringBuffer propertyBuf = new StringBuffer();
    
    for (Property property : sensorData.getProperties().getProperty()) {
      propertyBuf.append('(');
      propertyBuf.append(property.getKey());
      propertyBuf.append(" : ");
      //convert to megawatts
      power = Double.parseDouble(property.getValue());
      //power = power / 1000000.00;
      //propertyBuf.append(String.format("%.2f", String.valueOf(power)));
      propertyBuf.append(power);
      propertyBuf.append("), ");
    }
    
    propertyString = propertyBuf.toString();
    propertyString = propertyString.substring(0, propertyString.length() - 2);
    buf.append(String.format(format, "Properties", propertyString));
    
    return buf.toString();
  }
  
  /**
   * Gets the help string associated with the SensorData command.
   * 
   * @see org.wattdepot.cli.command.WattDepotCliCommand#getHelp()
   * @return Information on how to invoke the list sensor data time command.
   */
  @Override
  public String getHelp() {
    return "sensordata {source} timestamp {timestamp}\n"
      + "  Prints information about a single sensor data instance.\n";
  }
}
